package com.ruoyi.cms.controller.admin;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.cms.common.BaseController;
import com.ruoyi.cms.domain.Archives;
import com.ruoyi.cms.domain.Category;
import com.ruoyi.cms.domain.Form;
import com.ruoyi.cms.exception.CmsException;
import com.ruoyi.cms.exception.XssAndSqlException;
import com.ruoyi.cms.service.*;
import com.ruoyi.cms.util.ExceptionEnum;
import com.ruoyi.cms.util.RandomUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/cms")
public class DashboardController extends BaseController {
	@Autowired
	private DashboardService dashboardService;
	@Autowired
	private ArchivesService archivesService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private FormService formService;
    @Autowired
    private SystemService systemService;

    @GetMapping("/detail")
    public R<Map<String,Object>> getDetail() {
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        Map<String, Object> mv = new HashMap<>();
        Map<String, Integer> statistics = dashboardService.statistics();
        String dbVersion = dashboardService.selectDBVersion();
        Map<String, String> serverInfo = new HashMap<String, String>();
        serverInfo.put("jvmName", props.getProperty("java.vm.name"));
        serverInfo.put("jreVersion", props.getProperty("java.version"));
        serverInfo.put("javaPath", props.getProperty("java.home"));
        serverInfo.put("jvmTotalMemory", String.valueOf(r.totalMemory()));
        serverInfo.put("jvmFreeMemory", String.valueOf(r.freeMemory()));
        serverInfo.put("optName", props.getProperty("os.name"));
        serverInfo.put("optFrameWork", props.getProperty("os.arch"));
        serverInfo.put("dbVersion", dbVersion);

        List< Archives > list = archivesService.queryListByTop();
        list.stream().forEach(item -> {
            if(item.getTitle().length() > 20) {
                item.setTitle(item.getTitle().substring(0, 20)+"...");
            }
        });

        mv.put("newest", list);
        mv.put("statistics", statistics);
        mv.put("serverInfo", serverInfo);
        return R.ok(mv);
    }

    @GetMapping("/treeCategory")
    public R<List<Category>> getTreeCategory() {
        List< Category > categories = categoryService.queryListByPage(new HashMap<String, Object>());
        return R.ok(categories);
    }

    @GetMapping("/getCategoryList")
    public R<List<Category>> getCategoryList() {
        return R.ok(categoryService.getAllList());
    }

    @GetMapping("/getFormList")
    public R<List<Form>> getFormList() {
        return R.ok(formService.queryAll());
    }

    @PostMapping("/save/category")
    public R<String> saveCategory(@RequestBody Category category) throws CmsException {
        category.setId(IdUtil.getSnowflake().nextIdStr());
        category.setCode(RandomUtil.getCharAndNumr(8));
        category.setLevel(category.getParentId().equals("-1") ? "1" : category.getLevel());
        category.setParentId(StringUtils.isBlank(category.getParentId())? "-1" : category.getParentId());
        category.setCreateBy(LoginHelper.getLoginUser().getLoginId());
        category.setDefaultEditor("uc");
        category.setCreateTime(new Date());
        if(!"-1".equals(category.getParentId())) {
            Category parent = categoryService.selectById(category.getParentId());
            category.setCatSeq(parent.getCatSeq() + "." + category.getCode());
        }else {
            category.setCatSeq("." + category.getCode());
        }

        String coverTemp = StrUtil.isBlank(category.getCoverTemp()) ? "" : category.getCoverTemp();
        String listTemp = StrUtil.isBlank(category.getListTemp()) ? "" : category.getListTemp();
        String articleTemp = StrUtil.isBlank(category.getArticleTemp()) ? "" : category.getArticleTemp();

        if(coverTemp.contains("../") || coverTemp.contains("..\\")) {
            throw new XssAndSqlException(
                ExceptionEnum.XSS_SQL_EXCEPTION.getCode(),
                ExceptionEnum.XSS_SQL_EXCEPTION.getMessage(),
                "栏目封面模板文件名疑似不安全，详情：" + category.getCoverTemp());
        }
        if(listTemp.contains("../") || listTemp.contains("..\\")) {
            throw new XssAndSqlException(
                ExceptionEnum.XSS_SQL_EXCEPTION.getCode(),
                ExceptionEnum.XSS_SQL_EXCEPTION.getMessage(),
                "栏目列表模板文件名疑似不安全，详情：" + category.getListTemp());
        }
        if(articleTemp.contains("../") || articleTemp.contains("..\\")) {
            throw new XssAndSqlException(
                ExceptionEnum.XSS_SQL_EXCEPTION.getCode(),
                ExceptionEnum.XSS_SQL_EXCEPTION.getMessage(),
                "栏目内容页模板文件名疑似不安全，详情：" + category.getArticleTemp());
        }

        //处理模版
        if(StringUtils.isNotBlank(category.getCoverTemp()) && !category.getCoverTemp().startsWith("/")) {
            category.setCoverTemp("/" + category.getCoverTemp());
        }
        if(StringUtils.isNotBlank(category.getListTemp()) && !category.getListTemp().startsWith("/")) {
            category.setListTemp("/" + category.getListTemp());
        }
        if(StringUtils.isNotBlank(category.getArticleTemp()) && !category.getArticleTemp().startsWith("/")) {
            category.setArticleTemp("/" + category.getArticleTemp());
        }
        categoryService.save(category);
        return R.ok("添加成功");
    }

    @PostMapping("/update/category")
    public R<String> updateCategory(@RequestBody Category category) throws CmsException {
        category.setUpdateBy(LoginHelper.getLoginUser().getLoginId());
        category.setUpdateTime(new Date());
        String coverTemp = StrUtil.isBlank(category.getCoverTemp()) ? "" : category.getCoverTemp();
        String listTemp = StrUtil.isBlank(category.getListTemp()) ? "" : category.getListTemp();
        String articleTemp = StrUtil.isBlank(category.getArticleTemp()) ? "" : category.getArticleTemp();

        if(coverTemp.contains("../") || coverTemp.contains("..\\")) {
            throw new XssAndSqlException(
                ExceptionEnum.XSS_SQL_EXCEPTION.getCode(),
                ExceptionEnum.XSS_SQL_EXCEPTION.getMessage(),
                "栏目封面模板文件名疑似不安全，详情：" + category.getCoverTemp());
        }
        if(listTemp.contains("../") || listTemp.contains("..\\")) {
            throw new XssAndSqlException(
                ExceptionEnum.XSS_SQL_EXCEPTION.getCode(),
                ExceptionEnum.XSS_SQL_EXCEPTION.getMessage(),
                "栏目列表模板文件名疑似不安全，详情：" + category.getListTemp());
        }
        if(articleTemp.contains("../") || articleTemp.contains("..\\")) {
            throw new XssAndSqlException(
                ExceptionEnum.XSS_SQL_EXCEPTION.getCode(),
                ExceptionEnum.XSS_SQL_EXCEPTION.getMessage(),
                "栏目内容页模板文件名疑似不安全，详情：" + category.getArticleTemp());
        }

        //处理模版
        if(StringUtils.isNotBlank(category.getCoverTemp()) && !category.getCoverTemp().startsWith("/")) {
            category.setCoverTemp("/" + category.getCoverTemp());
        }
        if(StringUtils.isNotBlank(category.getListTemp()) && !category.getListTemp().startsWith("/")) {
            category.setListTemp("/" + category.getListTemp());
        }
        if(StringUtils.isNotBlank(category.getArticleTemp()) && !category.getArticleTemp().startsWith("/")) {
            category.setArticleTemp("/" + category.getArticleTemp());
        }
        int num = categoryService.update(category);
        return R.ok("修改成功");
    }

    @GetMapping("find/category/{id}")
    public R<Category> findCateGory(@PathVariable(value = "id", required = false)String id) {
        return R.ok(categoryService.selectById(id));
    }

    @PostMapping("delete/{id}")
    public int deleteCateGory(@PathVariable(value = "id", required = false)String id) throws CmsException {
        return categoryService.delete(id);
    }

    @RequestMapping("updateSystem")
    public R<String> updateSystem(@RequestBody com.ruoyi.cms.domain.System system) throws CmsException {
        systemService.update(system);
        return R.ok("修改成功");
    }

    @RequestMapping("getSystem")
    public R<com.ruoyi.cms.domain.System> getSystem() {
        return R.ok(systemService.getSystem());
    }

}
